using Arcane.Source.Utils;
using Godot;

namespace Arcane.Source.Client.Extensions;

public static class ImageExt
{
    public static void Stack(this Image bottom, Image top, int offsetX = 0, int offsetY = 0)
    {
        var w = Mathf.Min(bottom.GetWidth() - offsetX, top.GetWidth());
        var h = Mathf.Min(bottom.GetHeight() - offsetY, top.GetHeight());

        for (int y = 0; y < h; y++)
        {
            for (int x = 0; x < w; x++)
            {
                var topPix = top.GetPixel(x, y);
                if (topPix.A < 0.1f) continue;

                bottom.SetPixel(offsetX + x, offsetY + y, topPix);
            }
        }
    }

    public static void ToSilhouette(this Image img, Color color)
    {
        var (w, h) = (img.GetWidth(), img.GetHeight());
        for (int y = 0; y < h; y++)
        {
            for (int x = 0; x < w; x++)
            {
                var px = img.GetPixel(x, y);
                if (px.A > 0.1f)
                    img.SetPixel(x, y, color);
            }
        }
    }

    public static void GenOutline(this Image img, Color color)
    {
        var (w, h) = (img.GetWidth(), img.GetHeight());
        bool[,] outlinePx = new bool[w, h];

        for (int y = 0; y < h; y++)
        {
            for (int x = 0; x < w; x++)
            {
                var px = img.GetPixel(x, y);

                if (px.A > 0.1f) continue;

                if ((x + 1).InRange(0..w) && img.GetPixel(x + 1, y).A > 0.1f)
                {
                    outlinePx[x, y] = true;
                    continue;
                }

                if ((x - 1).InRange(0..w) && img.GetPixel(x - 1, y).A > 0.1f)
                {
                    outlinePx[x, y] = true;
                    continue;
                }

                if ((y + 1).InRange(0..h) && img.GetPixel(x, y + 1).A > 0.1f)
                {
                    outlinePx[x, y] = true;
                    continue;
                }

                if ((y - 1).InRange(0..h) && img.GetPixel(x, y - 1).A > 0.1f)
                {
                    outlinePx[x, y] = true;
                    continue;
                }
            }
        }

        for (int y = 0; y < h; y++)
            for (int x = 0; x < w; x++)
                if (outlinePx[x, y])
                    img.SetPixel(x, y, color);
    }
}